#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import Any

from cta.config.base_config import BaseConfig
from cta.config.time_sequence_config.rule_config import RuleConfig
from cta.interface.action.open_position.abstract_open_position_action import AbstractOpenPositionAction
from web.constants.datetime_format import DatetimeFormat
from web.constants.direction import Direction
from web.constants.k_line_movement_pattern import KLineMovementPattern
from web.domain.responsibility_chain_dto import ResponsibilityChainDto
from web.manager.log_manager import LogManager
from web.models import CommodityFutureInfo
from web.models.commodity_future_date_contract_data import CommodityFutureDateContractData
from web.models.quant2_account import Quant2Account
from web.models.quant2_commodity_future_filter import Quant2CommodityFutureFilter
from web.util.commodity_future_code_util import CommodityFutureCodeUtil
from web.util.datetime_util import DatetimeUtil
from web.util.fee_util import FeeUtil

Logger = LogManager.get_logger(__name__)

class RuleOpenPositionAction(AbstractOpenPositionAction):
    """
    规则策略，开仓期货
    """

    def exec(self, responsibility_chain_dto: ResponsibilityChainDto = None) -> Any:
        Logger.info("规则策略，开仓期货")

        transaction_date: str = DatetimeUtil.datetime_to_str(responsibility_chain_dto, DatetimeFormat.Date_Format)

        # 查询所有账号
        quant2_account_list: list[Quant2Account] = self.quant2_account_dao.find_all()
        for quant2_account in quant2_account_list:

            # 如果这个账号已经到达最大持仓记录数，则跳过
            if quant2_account.hold_commodity_future_number == RuleConfig.Max_Hold_Commodity_Future_Number:
                Logger.warning("账号[%s]持有期货数量已经到达[%s]，不再开仓", quant2_account.account_name, quant2_account.hold_commodity_future_number)
                continue

            # 查询所有没被持仓的期货
            quant2_commodity_future_filter_list: list[Quant2CommodityFutureFilter] = self.quant2_commodity_future_filter_dao.find_by_not_close_position_order_by_normalization_variance120_desc()
            if quant2_commodity_future_filter_list is not None and len(quant2_commodity_future_filter_list) > 0:
                for quant2_commodity_future_filter in quant2_commodity_future_filter_list:

                    # 如果这个账号已经到达最大持仓记录数，则跳过
                    if quant2_account.hold_commodity_future_number == RuleConfig.Max_Hold_Commodity_Future_Number:
                        Logger.warning("账号[%s]持有期货数量已经到达[%s]，不再开仓", quant2_account.account_name, quant2_account.hold_commodity_future_number)
                        break

                    # 查询期货记录，如果不存在则删除，并跳过
                    commodity_future_date_contract_data: CommodityFutureDateContractData = self.commodity_future_date_contract_data_dao.find_by_code_and_transaction_date(quant2_commodity_future_filter.code, transaction_date)
                    if commodity_future_date_contract_data is None:
                        Logger.warning("期货[%s]在日期[%s]没有交易记录，删除，并跳过", quant2_commodity_future_filter.code, transaction_date)
                        self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)
                        continue

                    # 判断是趋势形态还是震荡形态，判断是向上还是向下
                    if quant2_commodity_future_filter.normalization_variance120 >= RuleConfig.Variance120_Trend_Or_Fluctuation_Threshold:
                        # 趋势形态

                        # 牛熊线
                        bull_short_line = None
                        if commodity_future_date_contract_data.ma250 is not None and commodity_future_date_contract_data.bias250 <= RuleConfig.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias250 >= RuleConfig.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma250
                        elif commodity_future_date_contract_data.ma120 is not None and commodity_future_date_contract_data.bias120 <= RuleConfig.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias120 >= RuleConfig.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma120
                        elif commodity_future_date_contract_data.ma60 is not None and commodity_future_date_contract_data.bias60 <= RuleConfig.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias60 >= RuleConfig.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma60
                        elif commodity_future_date_contract_data.ma20 is not None and commodity_future_date_contract_data.bias20 <= RuleConfig.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias20 >= RuleConfig.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma20
                        elif commodity_future_date_contract_data.ma10 is not None and commodity_future_date_contract_data.bias10 <= RuleConfig.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias10 >= RuleConfig.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma10
                        elif commodity_future_date_contract_data.ma5 is not None and commodity_future_date_contract_data.bias5 <= RuleConfig.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias5 >= RuleConfig.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma5
                        elif bull_short_line == None:
                            # 如果最后任何bias指标都无法确定哪一根均线可以作为牛熊线的话，则将前一个交易日的收盘价作为牛熊线。注意：现在数据库中last_close_price字段没有空值
                            bull_short_line = commodity_future_date_contract_data.last_close_price

                        if commodity_future_date_contract_data.close_price >= bull_short_line:
                            Logger.info("期货[%s]属于趋势向上形态，逢低做多", quant2_commodity_future_filter.code)

                            # 开多单
                            self.open_long_position_when_trend_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Trend)

                        else:
                            Logger.info("期货[%s]属于趋势向下形态，逢高做空", quant2_commodity_future_filter.code)

                            # 开空单
                            self.open_short_position_when_trend_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Trend)

                    else:
                        # 震荡形态

                        # 根据最近几个交易日的60日均线判断震荡方向
                        n_date_commodity_future_date_contract_data_list: list[CommodityFutureDateContractData] = self.commodity_future_date_contract_data_dao.find_by_code_and_before_n_transaction_date_order_by_transaction_date_desc(quant2_commodity_future_filter.code, transaction_date, RuleConfig.N_Date_For_Ma60_Fluctuation_Up_Or_Down)
                        if n_date_commodity_future_date_contract_data_list is None or len(n_date_commodity_future_date_contract_data_list) != RuleConfig.N_Date_For_Ma60_Fluctuation_Up_Or_Down:
                            Logger.warning("日货[%s]交易记录不足[%s]条，不考虑开仓", quant2_commodity_future_filter.code, RuleConfig.N_Date_For_Ma60_Fluctuation_Up_Or_Down)
                            continue

                        # 如果收盘价在ma60的下方，在出现分型形态时，开多单
                        if commodity_future_date_contract_data.close_price < commodity_future_date_contract_data.ma60:
                            # 开多单
                            self.open_long_position_when_fluctuation_pattern(quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)

                        # 如果收盘价在ma60的上方，在出现分型形态时，开空单
                        if commodity_future_date_contract_data.close_price > commodity_future_date_contract_data.ma60:
                            # 开空单
                            self.open_short_position_when_fluctuation_pattern(quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)

                        # ma60_list: list[float] = list(map(lambda x:x.ma60, n_date_commodity_future_date_contract_data_list))
                        # is_increasing: bool = ListUtil.is_increasing_list(ma60_list)
                        # is_decreasing: bool = ListUtil.is_decreasing_list(ma60_list)
                        #
                        # if is_increasing:
                        #     # 震荡向上形态，应当逢低做多
                        #
                        #     # 如果收盘价在ma60的下方，在出现分型形态时，开多单
                        #     if commodity_future_date_contract_data.close_price < commodity_future_date_contract_data.ma60:
                        #         # 开多单
                        #         self.open_long_position_when_fluctuation_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)
                        #
                        # elif is_decreasing:
                        #     # 震荡向下形态，应当逢高做空
                        #
                        #     # 如果收盘价在ma60的上方，在出现分型形态时，开空单
                        #     if commodity_future_date_contract_data.close_price > commodity_future_date_contract_data.ma60:
                        #         # 开空单
                        #         self.open_short_position_when_fluctuation_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)
                        #
                        # else:
                        #     # 水平震荡形态，应当逢低做或逢低做多
                        #
                        #     # 如果收盘价在ma60的下方，在出现分型形态时，开多单
                        #     if commodity_future_date_contract_data.close_price < commodity_future_date_contract_data.ma60:
                        #         # 开多单
                        #         self.open_long_position_when_fluctuation_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)
                        #
                        #     # 如果收盘价在ma60的上方，在出现分型形态时，开空单
                        #     if commodity_future_date_contract_data.close_price > commodity_future_date_contract_data.ma60:
                        #         # 开空单
                        #         self.open_short_position_when_fluctuation_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)

                        # 简单线性回归
                        # commodity_future_date_contact_data_120_list: list[CommodityFutureDateContractData] = self.commodity_future_date_contract_data_dao.find_by_code_and_before_n_transaction_date_order_by_transaction_date_desc(quant2_commodity_future_filter.code, transaction_date, RuleConfig.Linear_Regression_Dimension)
                        # x = np.array(list(map(lambda x: float(x.close_price), commodity_future_date_contact_data_120_list)))
                        # y = np.array(list(range(len(commodity_future_date_contact_data_120_list))))
                        # # 计算斜率和截距
                        # slope, intercept = np.polyfit(x, y, 1)

                        # if slope >= RuleConfig.Linear_Regression_Slope_Threshold:
                        #     # 震荡向上形态，应当逢低做多
                        #
                        #     # 如果收盘价在线性回归线的下方，在出现分型形态时，开多单
                        #     if commodity_future_date_contract_data.close_price < slope * float(commodity_future_date_contract_data.close_price) + intercept:
                        #         # 开多单
                        #         self.open_long_position_when_fluctuation_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)
                        #         quant2_account.hold_commodity_future_number = quant2_account.hold_commodity_future_number + 1
                        #
                        # elif slope <= - RuleConfig.Linear_Regression_Slope_Threshold:
                        #     # 震荡向下形态，应当逢高做空
                        #
                        #     # 如果收盘价在线性回归线的上方，在出现分型形态时，开空单
                        #     if commodity_future_date_contract_data.close_price > slope * float(commodity_future_date_contract_data.close_price) + intercept:
                        #         # 开空单
                        #         self.open_short_position_when_fluctuation_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)
                        #         quant2_account.hold_commodity_future_number = quant2_account.hold_commodity_future_number + 1
                        # else:
                        #     # 水平震荡形态，应当逢低做或逢低做多
                        #
                        #     # 如果收盘价在线性回归线的下方，在出现分型形态时，开多单
                        #     if commodity_future_date_contract_data.close_price < slope * float(commodity_future_date_contract_data.close_price) + intercept:
                        #         # 开多单
                        #         self.open_long_position_when_fluctuation_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)
                        #         quant2_account.hold_commodity_future_number = quant2_account.hold_commodity_future_number + 1
                        #
                        #     # 如果收盘价在线性回归线的上方，在出现分型形态时，开空单
                        #     if commodity_future_date_contract_data.close_price > slope * float(commodity_future_date_contract_data.close_price) + intercept:
                        #         # 开空单
                        #         self.open_short_position_when_fluctuation_pattern(commodity_future_date_contract_data, quant2_commodity_future_filter, transaction_date, quant2_account, KLineMovementPattern.Fluctuation)
                        #         quant2_account.hold_commodity_future_number = quant2_account.hold_commodity_future_number + 1

            else:
                Logger.warning("表quant2_c_f_filter中没有满足开仓条件的记录")

        super().next(responsibility_chain_dto)

    def calculate_position(self, commodity_future_date_contract_data: CommodityFutureDateContractData, commodity_future_info: CommodityFutureInfo, quant2_account: Quant2Account):
        """
        计算仓位，如果返回None，则不开仓
        """

        # 如果期货的收盘价过高，或者资金资产太少，连一手也无法开仓，则直接查找下一个账号
        if FeeUtil.calculate_open_commodity_future_cost_and_fee(commodity_future_date_contract_data.close_price, commodity_future_info, 1) > quant2_account.capital_assets:
            return

        # 计算开仓多少手
        # 开仓多少手
        open_or_close_position_lot: int = 1
        while float(quant2_account.capital_assets) / BaseConfig.Max_Hold_Commodity_Future_Number >= FeeUtil.calculate_open_commodity_future_cost_and_fee(commodity_future_date_contract_data.close_price, commodity_future_info, open_or_close_position_lot):
            if FeeUtil.calculate_open_commodity_future_cost_and_fee(commodity_future_date_contract_data.close_price, commodity_future_info, open_or_close_position_lot) >= float(quant2_account.capital_assets) / BaseConfig.Max_Hold_Commodity_Future_Number:
                break
            open_or_close_position_lot = open_or_close_position_lot + 1
        if float(quant2_account.capital_assets) / BaseConfig.Max_Hold_Commodity_Future_Number < FeeUtil.calculate_open_commodity_future_cost_and_fee(commodity_future_date_contract_data.close_price, commodity_future_info, open_or_close_position_lot):
            if open_or_close_position_lot == 1:
                return None
            else:
                open_or_close_position_lot = open_or_close_position_lot - 1

        return open_or_close_position_lot

    def open_long_position_when_trend_pattern(self, commodity_future_date_contract_data: CommodityFutureDateContractData, quant2_commodity_future_filter: Quant2CommodityFutureFilter,
                           transaction_date: str, quant2_account: Quant2Account, k_line_movement_pattern: int):
        """
        趋势形态，开多单
        """

        Logger.info("期货[%s]趋势向上形态，开多单", quant2_commodity_future_filter.code)

        # 查询commodity_future_info记录（大小写不敏感的精确匹配查询）
        filter_dict = {'code__iexact': CommodityFutureCodeUtil.code_to_contract_code(quant2_commodity_future_filter.code)}
        commodity_future_info: CommodityFutureInfo = self.commodity_future_info_dao.find_one(filter_dict, dict(), list())

        # 查询期货记录
        filter_dict = {'code': quant2_commodity_future_filter.code, 'transaction_date': transaction_date}
        commodity_future_date_contract_data: CommodityFutureDateContractData = self.commodity_future_date_contract_data_dao.find_one(filter_dict, dict(), list())
        if commodity_future_date_contract_data is None:
            Logger.warning("期货在日期[%s]没有交易记录，从表quant2_c_f_filter表中删除这条记录，跳过这个期货", quant2_commodity_future_filter.code, transaction_date)

            # 从quant2_c_f_filter表中删除这条记录
            self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)
            return

        # 计算仓位，如果为None，则不开仓
        open_or_close_position_lot: int = self.calculate_position(commodity_future_date_contract_data, commodity_future_info, quant2_account)
        if open_or_close_position_lot is None:
            return

        # 向表quant2_c_f_transact_record中插入记录
        self.quant2_commodity_future_transaction_record_dao.insert_when_open_long_position(quant2_account.account_name, quant2_commodity_future_filter.code,
                                                                                           transaction_date, commodity_future_date_contract_data.close_price,
                                                                                           open_or_close_position_lot, commodity_future_info, Direction.Up,
                                                                                           k_line_movement_pattern)

        # 删除quant2_c_f_filter表中的记录
        self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)

        quant2_account.hold_commodity_future_number = quant2_account.hold_commodity_future_number + 1

    def open_short_position_when_trend_pattern(self, commodity_future_date_contract_data: CommodityFutureDateContractData, quant2_commodity_future_filter: Quant2CommodityFutureFilter,
                            transaction_date: str, quant2_account: Quant2Account, k_line_movement_pattern: int):
        """
        趋势形态，开空单
        """

        Logger.info("期货[%s]趋势向下形态，开空单", quant2_commodity_future_filter.code)

        # 查询commodity_future_info记录（大小写不敏感的精确匹配查询）
        filter_dict = {'code__iexact': CommodityFutureCodeUtil.code_to_contract_code(quant2_commodity_future_filter.code)}
        commodity_future_info: CommodityFutureInfo = self.commodity_future_info_dao.find_one(filter_dict, dict(), list())

        # 查询期货记录
        filter_dict = {'code': quant2_commodity_future_filter.code, 'transaction_date': transaction_date}
        commodity_future_date_contract_data: CommodityFutureDateContractData = self.commodity_future_date_contract_data_dao.find_one(filter_dict, dict(), list())
        if commodity_future_date_contract_data is None:
            Logger.warning("期货在日期[%s]没有交易记录，从表quant2_c_f_filter表中删除这条记录，跳过这个期货", quant2_commodity_future_filter.code, transaction_date)

            # 从quant2_c_f_filter表中删除这条记录
            self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)
            return

        # 如果期货的收盘价过高，或者资金资产太少，连一手也无法开仓，则直接查找下一个账号
        if FeeUtil.calculate_open_commodity_future_cost_and_fee(commodity_future_date_contract_data.close_price, commodity_future_info, 1) > quant2_account.capital_assets:
            return

        # 计算仓位，如果为None，则不开仓
        open_or_close_position_lot: int = self.calculate_position(commodity_future_date_contract_data, commodity_future_info, quant2_account)
        if open_or_close_position_lot is None:
            return

        # 向表quant2_c_f_transact_record中插入记录
        self.quant2_commodity_future_transaction_record_dao.insert_when_open_short_position(quant2_account.account_name, quant2_commodity_future_filter.code,
                                                                                            transaction_date, commodity_future_date_contract_data.close_price,
                                                                                            open_or_close_position_lot, commodity_future_info, Direction.Down,
                                                                                            k_line_movement_pattern)

        # 删除quant2_c_f_filter表中的记录
        self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)

        quant2_account.hold_commodity_future_number = quant2_account.hold_commodity_future_number + 1

    def open_long_position_when_fluctuation_pattern(self, quant2_commodity_future_filter: Quant2CommodityFutureFilter,
                           transaction_date: str, quant2_account: Quant2Account, k_line_movement_pattern: int):
        """
        震荡形态，开多单
        """

        # 查询上两条交易记录
        last_two_commodity_future_date_contract_data_list: list[CommodityFutureDateContractData] = self.commodity_future_date_contract_data_dao.find_by_code_and_before_n_transaction_date_order_by_transaction_date_desc(quant2_commodity_future_filter.code, transaction_date, 3)
        if last_two_commodity_future_date_contract_data_list is not None and len(last_two_commodity_future_date_contract_data_list) == 3 \
                and last_two_commodity_future_date_contract_data_list[0].close_price > last_two_commodity_future_date_contract_data_list[1].close_price \
                and last_two_commodity_future_date_contract_data_list[1].close_price > last_two_commodity_future_date_contract_data_list[2].close_price:
            Logger.info("期货[%s]震荡向上形态，并且分型也是向上，逢低做多", quant2_commodity_future_filter.code)

            # 查询commodity_future_info记录（大小写不敏感的精确匹配查询）
            filter_dict = {'code__iexact': CommodityFutureCodeUtil.code_to_contract_code(quant2_commodity_future_filter.code)}
            commodity_future_info: CommodityFutureInfo = self.commodity_future_info_dao.find_one(filter_dict, dict(), list())

            # 查询期货记录
            filter_dict = {'code': quant2_commodity_future_filter.code, 'transaction_date': transaction_date}
            commodity_future_date_contract_data: CommodityFutureDateContractData = self.commodity_future_date_contract_data_dao.find_one(filter_dict, dict(), list())
            if commodity_future_date_contract_data is None:
                Logger.warning("期货在日期[%s]没有交易记录，从表quant2_c_f_filter表中删除这条记录，跳过这个期货", quant2_commodity_future_filter.code, transaction_date)

                # 从quant2_c_f_filter表中删除这条记录
                self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)
                return

            # 计算仓位，如果为None，则不开仓
            open_or_close_position_lot: int = self.calculate_position(commodity_future_date_contract_data, commodity_future_info, quant2_account)
            if open_or_close_position_lot is None:
                return

            # 向表quant2_c_f_transact_record中插入记录
            self.quant2_commodity_future_transaction_record_dao.insert_when_open_long_position(quant2_account.account_name, quant2_commodity_future_filter.code,
                                                                                               transaction_date, commodity_future_date_contract_data.close_price,
                                                                                               open_or_close_position_lot, commodity_future_info, Direction.Up,
                                                                                               k_line_movement_pattern)

            # 删除quant2_c_f_filter表中的记录
            self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)

            quant2_account.hold_commodity_future_number = quant2_account.hold_commodity_future_number + 1

    def open_short_position_when_fluctuation_pattern(self, quant2_commodity_future_filter: Quant2CommodityFutureFilter,
                            transaction_date: str, quant2_account: Quant2Account, k_line_movement_pattern: int):
        """
        震荡形态，开空单
        """

        # 查询上两条交易记录
        last_two_commodity_future_date_contract_data_list: list[CommodityFutureDateContractData] = self.commodity_future_date_contract_data_dao.find_by_code_and_before_n_transaction_date_order_by_transaction_date_desc(quant2_commodity_future_filter.code, transaction_date, 3)
        if last_two_commodity_future_date_contract_data_list is not None and len(last_two_commodity_future_date_contract_data_list) == 3 \
                and last_two_commodity_future_date_contract_data_list[0].close_price < last_two_commodity_future_date_contract_data_list[1].close_price \
                and last_two_commodity_future_date_contract_data_list[1].close_price < last_two_commodity_future_date_contract_data_list[2].close_price:
            Logger.info("期货[%s]震荡向下形态，并且分型也是向下，逢高做空", quant2_commodity_future_filter.code)

            # 查询commodity_future_info记录（大小写不敏感的精确匹配查询）
            filter_dict = {'code__iexact': CommodityFutureCodeUtil.code_to_contract_code(quant2_commodity_future_filter.code)}
            commodity_future_info: CommodityFutureInfo = self.commodity_future_info_dao.find_one(filter_dict, dict(), list())

            # 查询期货记录
            filter_dict = {'code': quant2_commodity_future_filter.code, 'transaction_date': transaction_date}
            commodity_future_date_contract_data: CommodityFutureDateContractData = self.commodity_future_date_contract_data_dao.find_one(filter_dict, dict(), list())
            if commodity_future_date_contract_data is None:
                Logger.warning("期货在日期[%s]没有交易记录，从表quant2_c_f_filter表中删除这条记录，跳过这个期货", quant2_commodity_future_filter.code, transaction_date)

                # 从quant2_c_f_filter表中删除这条记录
                self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)
                return

            # 如果期货的收盘价过高，或者资金资产太少，连一手也无法开仓，则直接查找下一个账号
            if FeeUtil.calculate_open_commodity_future_cost_and_fee(commodity_future_date_contract_data.close_price, commodity_future_info, 1) > quant2_account.capital_assets:
                return

            # 计算仓位，如果为None，则不开仓
            open_or_close_position_lot: int = self.calculate_position(commodity_future_date_contract_data, commodity_future_info, quant2_account)
            if open_or_close_position_lot is None:
                return

            # 向表quant2_c_f_transact_record中插入记录
            self.quant2_commodity_future_transaction_record_dao.insert_when_open_short_position(quant2_account.account_name, quant2_commodity_future_filter.code,
                                                                                                transaction_date, commodity_future_date_contract_data.close_price,
                                                                                                open_or_close_position_lot, commodity_future_info, Direction.Down,
                                                                                                k_line_movement_pattern)

            # 删除quant2_c_f_filter表中的记录
            self.quant2_commodity_future_filter_dao.delete(quant2_commodity_future_filter)

            quant2_account.hold_commodity_future_number = quant2_account.hold_commodity_future_number + 1
